package org.cy.algorithm.chapter_05;

import org.cy.algorithm.util.AlgorithmUtil;

import java.util.HashMap;
import java.util.Map;

public class RandomAB_5_1_2 {
    private int bitCount;
    private int n;
    private int a;

    public RandomAB_5_1_2(int a, int b) {
        int n = b - a + 1;
        for (int i = 0; i < 32; i++) {
            if ((1 << i) >= n - 1) {
                bitCount = i + 1;
                break;
            }
        }
        System.out.println(bitCount);
        this.a = a;
        this.n = n;
    }

    // 根据random0_1函数，生成从a-别的随机数
    public int random() {
        // 转换成 0 到 (b - a + 1)，的随机数，结果 +a
        int result = 0;
        for (int i = 0; i < bitCount; i++) {
            result |= (AlgorithmUtil.random0_1() << i);
        }
        if (result > n - 1) {
            return random();
        }
        return result + a;
    }

    public static void main(String[] args) {
        RandomAB_5_1_2 randomAB512 = new RandomAB_5_1_2(10, 19);
        Map<Integer, Integer> countMap = new HashMap<>();
        for (int i = 0; i < 100000; i++) {
            int value = randomAB512.random();
            countMap.put(value, countMap.getOrDefault(value, 0) + 1);
        }

        for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}
